package br.com.iswe.gwt.ui.client.service;

import br.com.iswe.core.entidades.gwt.BeanMap;
import br.com.iswe.core.entidades.gwt.RemoteEntityObject;
import br.com.iswe.gwt.ui.client.FilterCallback;
import br.com.iswe.gwt.ui.client.FilterCallbackFactory;
import br.com.iswe.gwt.ui.client.QueryInfo;

import com.google.gwt.user.client.rpc.AsyncCallback;
@SuppressWarnings("unchecked")
public abstract class ServiceClientAbstract<E extends RemoteEntityObject>  {
	protected final String controllerName;
	
	protected static FilterCallbackFactory filterCallbackFactory;
		
	public ServiceClientAbstract(String controllerName) {
		this.controllerName = controllerName;
	}
	
	public ManyToManyClientAsyncContract getManyToManyClientAsyncContract(){
		throw new RuntimeException("getManyToManyClientAsyncContract() not implemented by concrete class.");
	}
	
	public void removerManyToMany(BeanMap beanMap, QueryInfo queryInfo, AsyncCallback<E> callback) {
		//RequestInfo requestInfo = new RequestInfo(ClientInfoContext.getClientInfoContext().getSessionInfo());
		getManyToManyClientAsyncContract().removerManyToMany(this.controllerName, beanMap,
				queryInfo, 
				getCallBack(callback));
	}
	public void associarManyToMany(BeanMap beanMap, QueryInfo queryInfo, AsyncCallback<E> callback) {
		//RequestInfo requestInfo = new RequestInfo(ClientInfoContext.getClientInfoContext().getSessionInfo());
		getManyToManyClientAsyncContract().associarManyToMany(this.controllerName, beanMap,
				queryInfo, 
				getCallBack(callback));
	}
	
	protected AsyncCallback getCallBack(AsyncCallback callback) {
		//caso tenha sido informado um filter, utilizar esse filter.
		if(filterCallbackFactory != null){
			FilterCallback delegate = filterCallbackFactory.getInstance();
			delegate.setDelegate(callback);
			return delegate;
		}
		else{
			return callback;
		}
	}

	/**
	 * FilterCallback : Utilizado como filtro de todos os calbacks q voltao do servidor.
	 */
	public static FilterCallbackFactory getFilterCallbackFactory() {
		return filterCallbackFactory;
	}
	public static void setFilterCallbackFactory(FilterCallbackFactory filterCallbackFactory) {
		BeanMapServiceClientImpl.filterCallbackFactory = filterCallbackFactory;
	}
	
}
